package com.example.ossdemo.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PolicyConditions;
import com.example.ossdemo.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.ldap.PagedResultsControl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author hang
 * @version 1.0
 * Create by 2022/8/23 9:15
 * @ClassName OssController
 * @Description TODO
 */
@Slf4j
@CrossOrigin
//@RestController
@RequestMapping("/thirdparty")
public class OssController {
    /*注入oss客户端操作对象*/
//    @Autowired
    private OSS ossClient;

    /*从配置文件中获取endpoint值*/
    @Value("${aliyun.oss.aliyunDomain}")
    private String endpoint;

    /*从配置文件中获取bucket值*/
//    @Value("${aliyun.oss.aliyunBucketName}")
//    private String bucket;

    /*从配置文件中获取accessId值*/
    @Value("${aliyun.oss.aliyunAccessKeyId}")
    private String accessId;

    @Value("${aliyun.oss.aliyunAccessKeySecret}")
    private String accessKey ;
//    // 填写Host名称，格式为https://bucketname.endpoint。
//    String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com";
//    // 设置上传回调URL，即回调服务器地址，用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后，把文件上传信息通过此回调URL发送给应用服务器。
//    String callbackUrl = "https://192.168.0.5:30000";
//    // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
//    String dir = "exampledir/";

    @RequestMapping("/oss/policy")

    public Map<String, String> policy(String bucket){

        // 创建OSSClient实例。
        ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        // host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint.substring(8);
        //上传的目录 以每天的日期为单位分目录
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format+"/";

        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

        /*必须返回json格式，因为上传时从data变量里取值*/
        return respMap;
    }
    @RequestMapping("/fileMessage")
    public ObjectMetadata fileMessage(String bucketname, String filename){
        // 创建OSSClient实例。
        ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        // 获取文件的全部元信息。
        ObjectMetadata metadata = ossClient.getObjectMetadata(bucketname, filename);
        System.out.println(metadata.getContentType());
        System.out.println(metadata.getLastModified());
//        System.out.println(metadata.getExpirationTime());
        ossClient.shutdown();
        return metadata;
    }
}
